package com.crazypos.security.handler;

import cn.hutool.core.bean.BeanUtil;
import com.crazypos.common.ApiRestResponse;
import com.crazypos.common.SecurityResponse;
import com.crazypos.common.utils.JWTTokenUtil;
import com.crazypos.config.JWTConfig;
import com.crazypos.pojo.UserEntity;
import com.crazypos.pojo.vo.LoginUserInfoVO;
import com.crazypos.security.entity.UserDetailEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 组装JWT
        UserDetailEntity loginUser = (UserDetailEntity) authentication.getPrincipal();

        String token = "";
        try {
            token = JWTTokenUtil.createToken(loginUser, 0);
        } catch (Exception e) {
            e.printStackTrace();
            SecurityResponse.reponseJson(
                    httpServletResponse,
                    ApiRestResponse.error()
            );
            return;
        }

        LoginUserInfoVO loginUserInfoVO = new LoginUserInfoVO();
        BeanUtil.copyProperties(loginUser, loginUserInfoVO);

        Map<String, Object> result = new HashMap<>();
        result.put(JWTConfig.tokenHeader, token);
        result.put("userInfo", loginUserInfoVO);

        httpServletResponse.setStatus(200);
        httpServletResponse.addHeader(JWTConfig.tokenHeader, token);

        SecurityResponse.reponseJson(
                httpServletResponse,
                ApiRestResponse.success(HttpStatus.OK.value(), result)
        );
    }
}
